import router from './router'
import store from '@/store'
import { getItem } from '@/utils/storage'
import $axios from '@/scripts/http'

router.beforeEach(async (to, from, next) => {
  // 校验需要登录的页面
  if (to.meta.needLogin) {
    let userInfo = JSON.parse(await getItem('userInfo'))
    if (!store.state.user.isLogin) {
      if (userInfo) {
        $axios.defaults.headers.common['token'] = userInfo.token
        store.commit('changeLoginStatus', true)
        store.commit('changeUser', userInfo.user)
      } else {
        next('/login')
      }
    }
  }
  next()
  window.scrollTo(0, 0)
})
